import { Component, Fragment } from "react"
import TodoItem from "./TodoItem";
class Todolist extends Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleKeyUp = this.handleKeyUp.bind(this)
    this.deleteClick =this.deleteClick.bind(this)
    this.state = {
      inputValue: '',
      list: []
    }
  }
  handleInputChange (e) {
    // console.log(e.target.value)
    this.setState({ inputValue: e.target.value })
  }
  handleKeyUp (e) {
    // console.log(e.keyCode)
    if (e.keyCode === 13 && this.state.inputValue !== "") {
      const list = [...this.state.list, this.state.inputValue]
      this.setState({
        list
      })
      this.setState({ inputValue: '' })
    }

  }
  deleteClick (index) {
    // console.log(index)
    let list = [...this.state.list]
    list.splice(index, 1);
    this.setState({
      list
    })
  }
  getItemList () {
    return this.state.list.map((value, index) => {
      return (
        <TodoItem content={value} key={index} index={index} deleteFunction={this.deleteClick}></TodoItem>
      )

    }
    )
  }
  render () {
    return (
      <Fragment>
        <input value={this.state.inputValue}
          onChange={this.handleInputChange}
          onKeyUp={this.handleKeyUp}
        />
        <ul>
          {this.getItemList()}
        </ul>
      </Fragment>
    )
  }

}

export default Todolist